package com.forhappy.light3ds8.tools;

import java.nio.ByteBuffer;

import android.text.TextUtils;
import android.util.Log;

public class DatasUtils {
	private static final String TAG = "DatasUtils";
	public static byte[] convertToBytes(char[] datas){
		byte[] byteDatas = new byte[datas.length];
		for(int i= 0; i < datas.length; i++){
			byteDatas[i] = (byte) datas[i];
		}
		return byteDatas;
	}
	public static String byteToHexStr(byte[] bytes){
		if(null == bytes || bytes.length == 0){
			return "";
		}
		return byteToHexStr(bytes, 0, bytes.length);
	}

	public static String byteToHexStr(byte[] bytes, int start, int count){
		if(null == bytes ){
			Log.e(TAG, "in byteToHex, bytes is null");
			return "";
		} else if(start < 0 || start + count > bytes.length){
			Log.e(TAG, "in byteToHex, start:" + start + ", count:" + count + " is invalied!");
			return "";
		}

		StringBuffer sb = new StringBuffer();
		for(int i = start; i < start + count; i++){
			String hexStr = Integer.toHexString(0XFF & bytes[i]);
			if(hexStr.length() == 1){
				hexStr = "0" + hexStr;
			}
			sb.append(hexStr).append(" ");
		}
//		for(byte b: bytes){
//			String hexStr = Integer.toHexString(b);
//			if(hexStr.length() == 1){
//				hexStr = "0" + hexStr;
//			}
//			sb.append(hexStr).append(" ");
//		}
		return sb.toString();
	}

	public static byte[] hexStrToBytes(String hexs){
		ByteBuffer buf = ByteBuffer.allocate(5000);
		byte[] retDatas = null;
		try{
			hexs = hexs.trim();
			if(TextUtils.isEmpty(hexs)){
				Log.i(TAG, "in hexToBytes hexs is empty");
				return new byte[]{};
			}
			String[]datas = hexs.split(" ");
			for(String data: datas){
				//earse blank
				if(TextUtils.isEmpty(data)){
					continue;
				}
				buf.put((byte)(0Xff & Integer.valueOf(data, 16)));
			}
			buf.flip();
			retDatas = new byte[buf.limit()];
			buf.get(retDatas);

		}catch(Exception e){
			Log.e(TAG, e.toString(), e);
		};
		return retDatas;
	}

	public static byte[] getFlorToFlorDatas(){
		byte[] datas = new byte[8 * 8 * 8];
		for(int i = 0; i < 8; i ++){
			for(int j = 0; j < 8; j++){
				for(int k =0; k< 8; k++){
					if(i == j){
						datas[ 8*(8*i +j) +k] = (byte) 0xFF;
					} else {
						datas[ 8*(8*i +j) +k] = 0;
					}
				}
			}
		}
		return datas;
	}
}
